﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Resources;
using System.Net;
using System.IO;

namespace GT5RemoteMobile
{
    public partial class Default : System.Web.UI.Page
    {
        string jsessionid;
        protected void Page_Load(object sender, EventArgs e)
        {
#if(!DEBUG)
            if (!Context.Request.IsSecureConnection)
                Response.Redirect("https://gt5mobile.com/");
#endif
            if (Settings.EnablePSNMessage == "true")
            {
                divMessage.Visible = true;
                lblMessage.Visible = true;
            }
            else
            {
                divMessage.Visible = false;
                lblMessage.Visible = false;
            }
            // need JSESSION ID for PSN login wrapping functionality
            if (!Page.IsPostBack)
            {
                HttpWebRequest request = WebRequest.Create(new Uri("https://store.playstation.com/external/index.vm?returnURL=https://us.gran-turismo.com/us/signin/index.do")) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    jsessionid = response.Headers["Set-Cookie"].Split(';')[0];
                }
            }
        }

        public bool RequestSuccessful(bool success)
        {
            if (success)
            {
                return true;
            }
            else
            {
                lblLoginError.Visible = true;
                divError.Visible = true;
                return false;
            }
        }

        protected void LoginPSN(object sender, EventArgs e)
        {
            int retryCounter = 5;
            bool success = false;
            string cookies = "";
            while(!success)
            {
                try
                {
                    if (retryCounter == 0)
                        break;
                     cookies = ACEGISecurityCheck();
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCounter--;
                }
            }

            if (!RequestSuccessful(success))
                return;

            string newUrl = "";
            string sessionId = "";

            success = false;
            retryCounter = 5;

            while (!success)
            {
                try
                {
                    if (retryCounter == 0)
                        break;
                    LoginPSN(cookies, out newUrl, out sessionId);
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCounter--;
                }
            }

            if (!RequestSuccessful(success))
                return;

            success = false;
            retryCounter = 5;

            while (!success)
            {
                try
                {
                    if (retryCounter == 0)
                        break;
                    JSessionCookieRequest(newUrl);
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCounter--;
                }
            }

            if (!RequestSuccessful(success))
                return;

            success = false;
            retryCounter = 5;

            while (!success)
            {
                try
                {
                    if (retryCounter == 0)
                        break;
                    SessionEnableRequest(newUrl);
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCounter--;
                }
            }

            if (!RequestSuccessful(success))
                return;

            string cookies2 = "";
            success = false;
            retryCounter = 5;

            while (!success)
            {
                try
                {
                    if (retryCounter == 0)
                        break;
                    cookies2 = ACEGISecurityCheckLocal();
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCounter--;
                }
            }

            if (!RequestSuccessful(success))
                return;

            success = false;
            retryCounter = 5;

            while (!success)
            {
                try
                {
                    if (retryCounter == 0)
                        break;
                    GetLocalSessionID(ref newUrl, ref sessionId, cookies2);
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCounter--;
                }
            }
            if (RequestSuccessful(success))
                Response.Redirect("landing.aspx");
            else
                return;
        }

        private void GetLocalSessionID(ref string newUrl, ref string sessionId, string cookies2)
        {
            HttpWebRequest sessionLogin = WebRequest.Create(new Uri("https://store.playstation.com/external/login.action")) as HttpWebRequest;
            sessionLogin.Method = "POST";
#if(DEBUG)
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //sessionLogin.Proxy = new WebProxy("localhost", 8888);
#endif
            sessionLogin.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            sessionLogin.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            sessionLogin.Referer = "https://store.playstation.com/external/index.vm?returnURL=" + Settings.appUrl;
            sessionLogin.AllowAutoRedirect = false;
            sessionLogin.Headers.Add("Cookie", cookies2);
            StreamWriter sessionStream = new StreamWriter(sessionLogin.GetRequestStream());
            sessionStream.Write("loginName=" + txtLogin.Value.Trim() + "&password=" + txtPassword.Value.Trim() + "&returnURL=" + HttpUtility.UrlEncode(Settings.appUrl));
            sessionStream.Close();

            newUrl = "";
            sessionId = "";
            using (HttpWebResponse response = sessionLogin.GetResponse() as HttpWebResponse)
            {
                sessionId = response.Headers["location"].ToString().Split('?')[1];
                Session.Add("localjsessionid", sessionId);
            }
        }

        private string ACEGISecurityCheckLocal()
        {
            HttpWebRequest acegiSecurityPost2 = WebRequest.Create(new Uri("https://store.playstation.com/j_acegi_external_security_check?target=/external/login.action")) as HttpWebRequest;
#if(DEBUG)
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //acegiSecurityPost2.Proxy = new WebProxy("localhost", 8888);
#endif
            acegiSecurityPost2.AllowAutoRedirect = false;
            acegiSecurityPost2.Method = "POST";
            acegiSecurityPost2.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            acegiSecurityPost2.ContentType = "application/x-www-form-urlencoded";
            acegiSecurityPost2.Referer = "https://store.playstation.com/external/index.vm?returnURL=http://gt5mobile.com";
            acegiSecurityPost2.Headers.Add("Cookie", jsessionid);
            StreamWriter acegiStream2 = new StreamWriter(acegiSecurityPost2.GetRequestStream());
            acegiStream2.Write("j_username=" + HttpUtility.UrlEncode(txtLogin.Value.Trim()) + "&j_password=" + HttpUtility.UrlEncode(txtPassword.Value.Trim()) + "&returnURL=http%3A%2F%2Fgt5mobile.com%2F");
            acegiStream2.Close();
            string cookies2;
            using (HttpWebResponse response = acegiSecurityPost2.GetResponse() as HttpWebResponse)
            {
                cookies2 = response.Headers["Set-Cookie"];
            }
            return cookies2;
        }

        private void SessionEnableRequest(string newUrl)
        {
            HttpWebRequest sessionRequest2 = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/")) as HttpWebRequest;
#if(DEBUG)
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //sessionRequest2.Proxy = new WebProxy("localhost", 8888);
#endif
            sessionRequest2.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            sessionRequest2.Referer = newUrl;
            sessionRequest2.Headers.Add("Cookie", jsessionid);

            using (HttpWebResponse response = sessionRequest2.GetResponse() as HttpWebResponse)
            {
            }
        }

        private void JSessionCookieRequest(string newUrl)
        {
            HttpWebRequest cookieRequest = WebRequest.Create(newUrl) as HttpWebRequest;
#if(DEBUG)
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //cookieRequest.Proxy = new WebProxy("localhost", 8888);
#endif
            cookieRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            cookieRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            cookieRequest.Headers.Add("Cookie", jsessionid);

            using (HttpWebResponse response = cookieRequest.GetResponse() as HttpWebResponse)
            {
                jsessionid = response.Headers["Set-Cookie"].Split(';')[0];
                Session.Add("jsessionid", jsessionid);
            }
        }

        private void LoginPSN(string cookies, out string newUrl, out string sessionId)
        {
            HttpWebRequest postLogin = WebRequest.Create(new Uri("https://store.playstation.com/external/login.action")) as HttpWebRequest;
            postLogin.Method = "POST";
#if(DEBUG)
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //postLogin.Proxy = new WebProxy("localhost", 8888);
#endif
            postLogin.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            postLogin.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            postLogin.Referer = "https://store.playstation.com/external/index.vm?returnURL=https://us.gran-turismo.com/us/signin/index.do";

            StreamWriter loginStream = new StreamWriter(postLogin.GetRequestStream());
            loginStream.Write("loginName=" + txtLogin.Value.Trim() + "&password=" + txtPassword.Value.Trim() + "&returnURL=https%3A%2F%2Fus.gran-turismo.com%2Fus%2Fsignin%2Findex.do");
            loginStream.Close();
            postLogin.Headers.Add("Cookie", cookies);
            newUrl = "";
            sessionId = "";
            using (HttpWebResponse response = postLogin.GetResponse() as HttpWebResponse)
            {
                try
                {
                    sessionId = response.ResponseUri.Query.Substring(1);
                }
                catch (ArgumentOutOfRangeException)
                {
                    lblLoginError.Visible = true;
                    divError.Visible = true;
                    throw new InvalidDataException("Invalid Username or Password");
                    //return;
                }
                newUrl = "https://us.gran-turismo.com/us/signin/signin.do?" + sessionId + "&url=https%3A%2F%2Fus.gran-turismo.com%2Fus%2F";
            }
        }

        private string ACEGISecurityCheck()
        {
            HttpWebRequest acegiSecurityPost = WebRequest.Create(new Uri("https://store.playstation.com/j_acegi_external_security_check?target=/external/login.action")) as HttpWebRequest;
#if(DEBUG)
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //acegiSecurityPost.Proxy = new WebProxy("localhost", 8888);
#endif
            acegiSecurityPost.AllowAutoRedirect = false;
            acegiSecurityPost.Method = "POST";
            acegiSecurityPost.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            acegiSecurityPost.ContentType = "application/x-www-form-urlencoded";
            acegiSecurityPost.Referer = "https://store.playstation.com/external/index.vm?returnURL=https://us.gran-turismo.com/us/signin/index.do";
            acegiSecurityPost.Headers.Add("Cookie", jsessionid);
            StreamWriter acegiStream = new StreamWriter(acegiSecurityPost.GetRequestStream());
            acegiStream.Write("j_username=" + HttpUtility.UrlEncode(txtLogin.Value.Trim()) + "&j_password=" + HttpUtility.UrlEncode(txtPassword.Value.Trim()) + "&returnURL=https%3A%2F%2Fus.gran-turismo.com%2Fus%2Fsignin%2Findex.do");
            acegiStream.Close();
            string cookies;
            using (HttpWebResponse response = acegiSecurityPost.GetResponse() as HttpWebResponse)
            {
                cookies = response.Headers["Set-Cookie"];
            }
            return cookies;
        }

        protected void GoLegacy(object sender, EventArgs e)
        {
            Response.Redirect("LegacyLogin.aspx");
        }
    }
}